package com.qyhl.webtv.module_news.news.goodlife.list;

import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.bumptech.glide.Glide;
import com.bumptech.glide.Priority;
import com.bumptech.glide.request.RequestOptions;
import com.gyf.immersionbar.ImmersionBar;
import com.qinanyu.bannerview.holder.SimpleHolder;
import com.qinanyu.bannerview.view.SimpleBannerView;
import com.qyhl.cloud.webtv.module_news.R;
import com.qyhl.cloud.webtv.module_news.R2;
import com.qyhl.webtv.basiclib.base.BaseActivity;
import com.qyhl.webtv.basiclib.base.BaseIViewPresenter;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.news.NewsBean;
import com.qyhl.webtv.commonlib.utils.router.RouterManager;
import com.qyhl.webtv.commonlib.utils.view.MyListView;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.umeng.analytics.MobclickAgent;
import com.weavey.loading.lib.LoadingLayout;
import com.zhy.adapter.abslistview.CommonAdapter;
import com.zhy.adapter.abslistview.ViewHolder;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import es.dmoral.toasty.Toasty;

/**
 * Created by qyhl on 2017/11/27.
 * 新趣汇子栏目列表
 */

@Route(path = ARouterPathConstant.GLIFE_LIST)
public class GoodLifeListActivity extends BaseActivity implements GoodLifeListContract.GoodLifeListView {
    @BindView(R2.id.title)
    TextView title;
    @BindView(R2.id.banner)
    SimpleBannerView banner;
    @BindView(R2.id.listview)
    MyListView listview;
    @BindView(R2.id.scrollview)
    ScrollView scrollview;
    @BindView(R2.id.refresh)
    SmartRefreshLayout refresh;
    @BindView(R2.id.load_mask)
    LoadingLayout loadMask;
    @BindView(R2.id.back_btn)
    ImageView backBtn;

    private GoodLifeListPresenter mPresenter;
    @Autowired(name = "id")
    String id;//栏目id
    private String lastId;//最后一条id
    @Autowired(name = "title")
    String mTitle;//标题

    private List<NewsBean> mList;
    private List<NewsBean> indexList;

    private RequestOptions options;

    private int topNum;//置顶数

    private CommonAdapter<NewsBean> commonAdapter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    protected int getContentView() {
        return R.layout.news_activity_goodlife_list;
    }

    @Override
    protected void setImmersionBar(ImmersionBar mImmersionBar) {
        setDefaultImmerBar();
    }

    @Override
    protected BaseIViewPresenter initBaseIViewPresenter() {
        return null;
    }

    @Override
    protected void init() {
        mPresenter = new GoodLifeListPresenter(this);
        lastId = "0";
        initView();

    }

    @Override
    protected void setListener() {
        setListeners();
        mPresenter.getTopNum(id);
    }

    /**
     * 初始化
     */
    private void initView() {
        mList = new ArrayList<>();
        //设置标题
        title.setText(mTitle);

        loadMask.setStatus(LoadingLayout.Loading);

        //设置刷新控件
        refresh.setRefreshHeader(new MaterialHeader(this));
        refresh.setRefreshFooter(new ClassicsFooter(this));
        refresh.setEnableLoadMore(true);
        refresh.setDisableContentWhenRefresh(true);
        refresh.setDisableContentWhenLoading(true);

        //glide 配置
        options = new RequestOptions()
                .placeholder(R.drawable.cover_large_default)
                .error(R.drawable.cover_large_default)
                .priority(Priority.HIGH);

        commonAdapter = new CommonAdapter<NewsBean>(this, R.layout.news_item_glife_list, mList) {
            @Override
            protected void convert(ViewHolder viewHolder, NewsBean item, int position) {
                TextView title = viewHolder.getView(R.id.title);
                TextView summary = viewHolder.getView(R.id.summary);
                ImageView cover = viewHolder.getView(R.id.cover);

                title.setText(item.getTitle());

                if (StringUtils.isNotEmpty(item.getSummary())) {
                    summary.setVisibility(View.VISIBLE);
                    summary.setText(item.getSummary());
                } else {
                    summary.setVisibility(View.GONE);
                }

                Glide.with(GoodLifeListActivity.this)
                        .load(item.getLogo())
                        .apply(options)
                        .into(cover);
            }
        };
        listview.setAdapter(commonAdapter);
        scrollview.scrollTo(0, 0);
    }

    /**
     * 设置监听
     */
    private void setListeners() {
        listview.setOnItemClickListener((parent, view, position, id) -> {
            Bundle bundle = new Bundle();
            bundle.putString("newsId", mList.get(position).getID());
            RouterManager.router(ARouterPathConstant.GOOD_LIFE_DETAIL,bundle);
        });

        //轮播点击
        banner.setOnItemClickListener(position -> {
            Bundle bundle = new Bundle();
            bundle.putString("newsId", indexList.get(position).getID());
            RouterManager.router(ARouterPathConstant.GOOD_LIFE_DETAIL,bundle,R.anim.open_next, R.anim.close_main);

        });

        //刷新监听
        refresh.setOnRefreshListener(refreshlayout -> mPresenter.getTopNum(id));

        //加载监听
        refresh.setOnLoadMoreListener(refreshlayout -> mPresenter.getData(id, lastId));

        //出错重试监听
        loadMask.setOnReloadListener(v -> {
            loadMask.setReloadButtonText("加载中...");
            mPresenter.getTopNum(id);
        });

        //返回
        backBtn.setOnClickListener(view -> finish());
    }

    /**
     * 设置置顶数
     *
     * @param num
     */
    @Override
    public void setTopNum(int num) {
        topNum = num;
        lastId = "0";
        mPresenter.getData(id, lastId);
    }

    /**
     * 获取置顶数出错
     */
    @Override
    public void topNumError() {
        topNum = 0;
        lastId = "0";
        mPresenter.getData(id, lastId);
    }

    /**
     * 添加数据
     *
     * @param beanList
     */
    @Override
    public void setData(List<NewsBean> beanList, boolean isMore) {
        refresh.finishLoadMore();
        refresh.finishRefresh();
        loadMask.setStatus(LoadingLayout.Success);
        loadMask.setReloadButtonText("点击重试~~");

        try {
            lastId = beanList.get(beanList.size() - 1).getID();
        } catch (Exception e) {
            lastId = "0";
        }

        if (isMore) {//加载
            mList.addAll(beanList);
            commonAdapter.notifyDataSetChanged();
        } else {//刷新
            if (topNum != 0) {
                banner.setVisibility(View.VISIBLE);
                indexList = new ArrayList<>();
                if (beanList.size() > topNum) {
                    for (int i = 0; i < topNum; i++) {
                        indexList.add(beanList.get(i));
                    }

                    beanList.removeAll(indexList);
                    mList.clear();
                    mList.addAll(beanList);
                    commonAdapter.notifyDataSetChanged();
                } else {
                    indexList = beanList;
                }

                List<String> titleNames = new ArrayList<>();
                for (int i = 0; i < beanList.size(); i++) {
                    titleNames.add(beanList.get(i).getTitle());
                }
                String[] titleStrings = new String[titleNames.size()];
                titleNames.toArray(titleStrings);
                //当只有一张轮播时
                if (beanList.size() == 1) {
                    banner.setCanLoop(false);
                    banner.setTextBanner(titleStrings[0]);
                } else {
                    banner.setCanLoop(true);
                }

                //初始化轮播信息
                banner.setPages(() -> new BannerViewHolder(), indexList).startTurning(3000)
                        .setPageIndicator(new int[]{R.drawable.news_banner_indicator_off, R.drawable.news_banner_indicator_on}, titleStrings)
                        .setPageIndicatorAlign(SimpleBannerView.PageIndicatorAlign.ALIGN_PARENT_RIGHT);

            } else {
                banner.setVisibility(View.GONE);
                mList.clear();
                mList.addAll(beanList);
            }
        }

    }

    /**
     * 无网络
     *
     * @param msg
     */
    @Override
    public void setNetError(String msg) {
        refresh.finishLoadMore();
        refresh.finishRefresh();
        loadMask.setNoNetworkText(msg);
        loadMask.setStatus(LoadingLayout.No_Network);
        loadMask.setReloadButtonText("点击重试~~");
    }

    /**
     * 出错
     *
     * @param msg
     */
    @Override
    public void setError(String msg) {
        refresh.finishLoadMore();
        refresh.finishRefresh();
        loadMask.setErrorText(msg);
        loadMask.setStatus(LoadingLayout.Error);
        loadMask.setReloadButtonText("点击重试~~");
    }

    /**
     * 无内容
     *
     * @param msg
     */
    @Override
    public void setEmpty(String msg) {
        refresh.finishLoadMore();
        refresh.finishRefresh();
        loadMask.setEmptyText(msg);
        loadMask.setStatus(LoadingLayout.Empty);
        loadMask.setReloadButtonText("点击重试~~");
    }

    /**
     * Toast
     *
     * @param msg
     */
    @Override
    public void showMessage(String msg) {
        refresh.finishLoadMore();
        refresh.finishRefresh();
        Toasty.normal(GoodLifeListActivity.this, msg, Toast.LENGTH_SHORT).show();
        loadMask.setReloadButtonText("点击重试~~");
    }

    @Override
    public void showLog(String msg) {
        refresh.finishLoadMore();
        refresh.finishRefresh();
        loadMask.setReloadButtonText("点击重试~~");
    }

    /**
     * 轮播holder
     */
    class BannerViewHolder implements SimpleHolder<NewsBean> {
        private ImageView imageView;

        @Override
        public View createView(Context context) {
            imageView = new ImageView(context);
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            return imageView;
        }

        @Override
        public void UpdateUI(Context context, int position, NewsBean data) {
            Glide.with(context.getApplicationContext())
                    .load(data.getLogo())
                    .apply(options)
                    .into(imageView);
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
        //baidu
        //umeng
        MobclickAgent.onPageStart("新趣汇子栏目");
        MobclickAgent.onResume(this);
    }


    @Override
    protected void onPause() {
        super.onPause();
        //baidu
        //umeng
        MobclickAgent.onPageEnd("新趣汇子栏目");
        MobclickAgent.onPause(this);
    }

}
